import useLocalStorage from '@/entrypoints/hook/useLocalStorage';
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from './ui/pagination';
import { getPageList } from '@/lib/utils';
import { Label } from '@radix-ui/react-label';
import { toast } from 'sonner';
import { Input } from './ui/input';
import { PaginationState, Table } from '@tanstack/react-table';
import { useId } from 'react';

type Props<TTableData, TPageParams> = {
  children?: React.ReactNode;
  className?: string;
  setPagination: React.Dispatch<React.SetStateAction<PaginationState>>;
  setStoredValue: React.Dispatch<React.SetStateAction<TPageParams>>;
  storedValue: TPageParams;
  table: Table<TTableData>;
};

export default function TablePagination<
  TTableData,
  TPageParams extends {
    pageSize: number;
  },
>({
  children,
  className,
  setStoredValue,
  setPagination,
  table,
  storedValue,
  ...props
}: Props<TTableData, TPageParams>) {
  const id = useId();
  return (
    <Pagination>
      <PaginationContent>
        <div className="inline-flex items-center">
          <div className="inline-flex gap-2 items-center">
            <Label className="whitespace-nowrap mb-0" htmlFor={id + 'page-size'}>
              分页页数:
            </Label>
            <Input
              value={storedValue.pageSize}
              type="number"
              onChange={(event) => {
                const newPageSize = Number(event.target.value);
                setStoredValue((prev) => ({
                  ...prev,
                  pageSize: newPageSize,
                }));
                setPagination({
                  pageIndex: 0,
                  pageSize: newPageSize,
                });
              }}
              id={id + 'page-size'}
              className="h-10 rounded-md border border-input px-3 py-2 w-16"
            />
          </div>
        </div>
        <PaginationItem>
          <PaginationPrevious
            className="cursor-pointer select-none"
            onClick={() => {
              if (table.getCanPreviousPage()) {
                table.previousPage();
              }
            }}
          />
        </PaginationItem>
        {table.getPageCount() > 0
          ? (() => {
              const total = table.getPageCount();
              const current = table.getState().pagination.pageIndex + 1;
              const showPageCount = 3;
              const showPageList = getPageList(total, current, showPageCount);
              return showPageList.map((page) => {
                return (
                  <PaginationItem key={page}>
                    {page === -Infinity || page === Infinity ? (
                      <PaginationEllipsis></PaginationEllipsis>
                    ) : (
                      <PaginationLink
                        className="cursor-pointer select-none"
                        isActive={current === page}
                        onClick={() => {
                          setPagination({
                            pageIndex: page - 1,
                            pageSize: storedValue.pageSize,
                          });
                        }}
                      >
                        {page}
                      </PaginationLink>
                    )}
                  </PaginationItem>
                );
              });
            })()
          : null}
        <PaginationItem>
          <PaginationNext
            className="cursor-pointer select-none"
            onClick={() => {
              if (table.getCanNextPage()) {
                table.nextPage();
              }
            }}
          />
        </PaginationItem>
        <div className="flex px-3 gap-2 items-center py-4">
          <Input
            value={table.getState().pagination.pageIndex + 1}
            type="number"
            onChange={(event) => {
              const page = event.target.value ? Number(event.target.value) : 1;
              const total = table.getPageCount();
              if (page > total) {
                toast.info('总页数是 ' + total);
              }
              if (page < 1) {
                toast.info('已经超出首页了');
              }
              setPagination({
                pageIndex: page - 1,
                pageSize: storedValue.pageSize,
              });
            }}
            className="h-10 rounded-md border border-input px-3 py-2 w-[70px]"
          />
        </div>
        <span>{`${table.getState().pagination.pageIndex + 1} of ${table.getPageCount()} (${table.getPrePaginationRowModel().rows.length})`}</span>
      </PaginationContent>
    </Pagination>
  );
}
